/*
ONEGAME
Copyright (C) 2009  Pablo Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package one.tool;

import java.awt.Cursor;
import java.awt.Event;
import java.awt.Window;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import one.dialog.DefaultEditorTableModel;
import one.dialog.FieldEditor;
import one.dialog.IPropertiesDialogEventListener;
import one.dialog.PropertiesDlg;
import one.language.HelpLabels;
import one.language.Labels;
import one.main.MapPanel;
import one.map.ILayerMap;
import one.project.IProject;
import one.project.ISystemData;

/**
 * Tool Panel
 * @author Pablo Caballero
 * @version 1.0 22-jun-2009
 */
public class ToolPanel extends javax.swing.JPanel implements IPropertiesDialogEventListener {

    /**
     * Cursor when the program is busy
     */
    private static final Cursor waitingCursor = new Cursor(Cursor.WAIT_CURSOR);
    /**
     * The project
     */
    protected IProject project;
    /**
     * The map panel
     */
    protected MapPanel mapPanel;

    /** Creates new form ToolPanel */
    public ToolPanel() {
        initComponents();
    }

    /**
     * Get the value of project
     * @return the value of project
     */
    public IProject getProject() {
        return project;
    }

    /**
     * Sets the project in the model of the tool panel
     * @param project the project
     */
    public void setProject(IProject project) {
        Cursor prevcursor;

        prevcursor = getCursor();
        this.project = project;
        setCursor(waitingCursor);
        ((ToolModel) treeTools.getModel()).setProject(project);
        ((ToolModel) treeTools.getModel()).updateStructure();
        setCursor(prevcursor);
    }

    /**
     * Adds a new layer
     */
    private void addLayer() {
        Cursor prevcursor;

        prevcursor = getCursor();
        setCursor(waitingCursor);
        ((ToolModel) treeTools.getModel()).newLayer();
        mapPanel.repaint();
        setCursor(prevcursor);
    }

    /**
     * Deletes the selected layer
     */
    private void deleteLayer() {
        int[] rows;
        ArrayList<ILayerMap> delLayers;
        Cursor prevcursor;

        prevcursor = getCursor();
        setCursor(waitingCursor);
        delLayers = new ArrayList<ILayerMap>();
        rows = treeTools.getSelectionRows();
        for (int i = 0; i < rows.length; i++) {
            if (treeTools.getPathForRow(rows[i]).getLastPathComponent() instanceof ILayerMap) {
                delLayers.add((ILayerMap) treeTools.getPathForRow(rows[i]).getLastPathComponent());
            }
        }
        if (delLayers.size() > 0) {
            ((ToolModel) treeTools.getModel()).deleteLayers(delLayers);
        }
        setCursor(prevcursor);
    }

    /**
     * Opens the properties of the selected element
     */
    private void doubleClick() {
        Object obj;

        obj = treeTools.getLastSelectedPathComponent();

        if (treeTools.getSelectionCount() > 0) {
            treeTools.expandRow(treeTools.getSelectionRows()[0]);
        }

        if (obj instanceof ISystemData) {
            showSystemDataProperties();
        } else if (obj instanceof ILayerMap) {
            JOptionPane.showMessageDialog(this, obj.toString());
        }
    }

    /**
     * Gets the window owner
     * @return the window owner
     */
    private Window getWindowAncestor() {
        return SwingUtilities.getWindowAncestor(this);
    }

    /**
     * Shows the properties of the system data
     */
    private void showSystemDataProperties() {
        PropertiesDlg propertiesDlg = new PropertiesDlg(getWindowAncestor());
        DefaultEditorTableModel model = propertiesDlg.getModel();
        Vector<FieldEditor> fields = model.getFields();
        fields.add(new FieldEditor("getProjectName", "setProjectName", getProject().getSystemData(), Labels.getString("SYSTEMDATA_PROJECT_NAME"), HelpLabels.getString("SYSTEMDATA_PROJECTNAME_TITLE"), HelpLabels.getString("SYSTEMDATA_PROJECTNAME_DESCRIPTION")));
        fields.add(new FieldEditor("getAuthor", "setAuthor", getProject().getSystemData(), Labels.getString("SYSTEMDATA_PROJECT_AUTHOR"), HelpLabels.getString("SYSTEMDATA_AUTHOR_TITLE"), HelpLabels.getString("SYSTEMDATA_AUTHOR_DESCRIPTION")));
        propertiesDlg.addPropertiesListener(this);
        propertiesDlg.setVisible(true);
    }

    public void fieldChanged(Event evt) {
        ((ToolModel) treeTools.getModel()).updateStructure();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolsPopUpMenu = new javax.swing.JPopupMenu();
        mnItmNewLayer = new javax.swing.JMenuItem();
        mnItmDeleteLayer = new javax.swing.JMenuItem();
        scrTools = new javax.swing.JScrollPane();
        treeTools = new javax.swing.JTree();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("one/language/labels"); // NOI18N
        mnItmNewLayer.setText(bundle.getString("TOOLPANEL_NEWLAYER")); // NOI18N
        mnItmNewLayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmNewLayerActionPerformed(evt);
            }
        });
        toolsPopUpMenu.add(mnItmNewLayer);

        mnItmDeleteLayer.setText(bundle.getString("TOOLPANEL_DELETELAYER")); // NOI18N
        mnItmDeleteLayer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmDeleteLayerActionPerformed(evt);
            }
        });
        toolsPopUpMenu.add(mnItmDeleteLayer);

        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.LINE_AXIS));

        treeTools.setModel(new ToolModel());
        treeTools.setComponentPopupMenu(toolsPopUpMenu);
        treeTools.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeToolsMouseClicked(evt);
            }
        });
        scrTools.setViewportView(treeTools);

        add(scrTools);
    }// </editor-fold>//GEN-END:initComponents

	private void mnItmNewLayerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmNewLayerActionPerformed
            addLayer();
}//GEN-LAST:event_mnItmNewLayerActionPerformed

	private void mnItmDeleteLayerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmDeleteLayerActionPerformed
            deleteLayer();
}//GEN-LAST:event_mnItmDeleteLayerActionPerformed

	private void treeToolsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeToolsMouseClicked
            if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() >= 2) {
                doubleClick();
            }
	}//GEN-LAST:event_treeToolsMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem mnItmDeleteLayer;
    private javax.swing.JMenuItem mnItmNewLayer;
    private javax.swing.JScrollPane scrTools;
    private javax.swing.JPopupMenu toolsPopUpMenu;
    private javax.swing.JTree treeTools;
    // End of variables declaration//GEN-END:variables

    public void setMapPanel(MapPanel mapPanel) {
        this.mapPanel = mapPanel;
    }
}
